//
//  ViewController.m
//  BiuWeather
//
//  Created by 楼楚 on 16/3/6.
//  Copyright © 2016年 Chu Lou. All rights reserved.
//

#define IS_IOS7 ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7)
#define IS_IOS8 ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8)
//主界面
#import "weatherView.h"
#import "ForecastControllerViewController.h"

#import "MBProgressHUD.h"
#import "LocationManager.h"

//获取网络数据
#import "GetWeatherData.h"
#import "WeatherData.h"

#import "ViewController.h"

@interface ViewController ()<CLLocationManagerDelegate,UITableViewDelegate,weatherViewDelegate,GetWeatherDataDelegate,UIViewControllerTransitioningDelegate,MBProgressHUDDelegate,LocationManagerDelegate>{
    CLGeocoder         *_geocoder;
    MBProgressHUD      *_updatingHUD;
    int a;
    }
@property (nonatomic,strong)  LocationManager      *locationManager;
@property (nonatomic,strong)  GetWeatherData       *getWeatherData;
@property (nonatomic,strong)  UILabel              *textLabel;
@property (nonatomic,strong)  weatherView          *weatherView;
@property (nonatomic,strong)  NSString             *cityName;
@property (nonatomic,strong)  NSString             *sublocalityName;
@property (nonatomic,strong)  NSString             *cityCNName;
@property (nonatomic, strong) CALayer              *movedMask;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    self.locationManager = [[LocationManager alloc]init];
    self.locationManager.delegate = self;
    [self.locationManager start];
    a = 0 ;
    
    _updatingHUD = [[MBProgressHUD alloc]initWithView:self.view];
    [self.view addSubview:_updatingHUD];
    [self.view bringSubviewToFront:_updatingHUD];
    _updatingHUD.delegate = self;
    _updatingHUD.labelText = @"正在刷新";
    [_updatingHUD show:YES];
    self.weatherView = [[weatherView alloc]initWithFrame:self.view.bounds];
    self.weatherView.layer.masksToBounds = YES;
    self.weatherView.delegate = self;
    [self.weatherView buildView];
    [self.view addSubview:self.weatherView];
    
    self.getWeatherData = [GetWeatherData new];
    self.getWeatherData.delegate = self;
//    [self.getWeatherData getData];
//    self.cityCNName = @"杭州市";
}
- (void)mapManager:(LocationManager *)manager didUpdateAndGetLastCLLocation:(CLLocation *)location{
    NSLog(@"定位成功");
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    _geocoder = [[CLGeocoder alloc]init];
    [_geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        CLPlacemark *placemark=[placemarks lastObject];
        
        NSString *str1 = [placemark.addressDictionary objectForKey:@"SubLocality"];
        NSString *str2 = [placemark.addressDictionary objectForKey:@"City"];
        self.cityCNName = str1 ;
        
        NSString *city  = [str1 substringToIndex:([str1  length]-1)];
        NSString *subcity = [str2 substringToIndex:([str2  length]-1)];
        NSString *city1 = [NSString stringWithFormat:@"city=%@",city];
        NSString *city2 = [NSString stringWithFormat:@"city=%@",subcity];
        self.sublocalityName = [city1 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        self.cityName = [city2 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSLog(@"%@",self.cityName);
        [self performSelector:@selector(delayRunEvent:)
                   withObject:self.sublocalityName
                   afterDelay:0.3f];
    }];
}
#pragma mark - 刷新时的动画
//TODO 删除ProgressHUD 增加刷新动画  （音乐波形条）
- (void)UpdatingView{
    self.view.backgroundColor = [UIColor blackColor];
    
    CAEmitterLayer *snowEmitter = [CAEmitterLayer layer];
    //    设置发射源位置、尺寸大小，发射模式、发射源形状
    //发射源设置在view外面，效果逼真一些
    snowEmitter.emitterPosition = CGPointMake(120,-120);
    snowEmitter.emitterSize = self.view.bounds.size;
    snowEmitter.emitterMode  = kCAEmitterLayerSurface;
    snowEmitter.emitterShape = kCAEmitterLayerLine;
    //    创建雪花粒子 设置名称
    CAEmitterCell *snowflake = [CAEmitterCell emitterCell];
    snowflake.name = @"snow";
    
    //     粒子参数的速度乘数因子
    snowflake.birthRate = 20.0;
    snowflake.lifetime  = 120.0;
    
    // 粒子速度
    snowflake.velocity =10.0;
    
    // 粒子的速度范围
    snowflake.velocityRange = 10;
    
    // 粒子y方向的加速度分量
    snowflake.yAcceleration = 2;
    
    // 周围发射角度
    snowflake.emissionRange = 0.5 * M_PI;
    
    // 子旋转角度范围
    snowflake.spinRange = 0.25 * M_PI;
    snowflake.contents  = (id)[[UIImage imageNamed:@"snow"] CGImage];
    
    // 设置雪花形状的粒子的颜色
    //以下设置雪花可以是colorful
        snowflake.color      = [[UIColor whiteColor] CGColor];
        snowflake.redRange   = 2.f;
        snowflake.greenRange = 2.f;
        snowflake.blueRange  = 2.f;
    //设置雪花为纯白
//    snowflake.color = [[UIColor whiteColor]CGColor];
    
    snowflake.scaleRange = 0.6f;
    snowflake.scale      = 0.7f;
    
    snowEmitter.shadowOpacity = 1.0;
    snowEmitter.shadowRadius  = 0.0;
    snowEmitter.shadowOffset  = CGSizeMake(0.0, 0.0);
    // 粒子边缘的颜色
    snowEmitter.shadowColor  = [[UIColor whiteColor] CGColor];
    
    // 添加粒子
    snowEmitter.emitterCells = @[snowflake];
    
    // 将粒子Layer添加进图层中
    [self.view.layer addSublayer:snowEmitter];
    // 加入遮罩有意想不到的效果
    // 形成遮罩
    UIImage *image      = [UIImage imageNamed:@"alpha"];
        _movedMask          = [CALayer layer];
        _movedMask.frame    = (CGRect){CGPointZero, image.size};
        _movedMask.contents = (__bridge id)(image.CGImage);
        _movedMask.position = self.view.center;
        snowEmitter.mask    = _movedMask;
    // 拖拽的View
    UIView *dragView = [[UIView alloc] initWithFrame:(CGRect){CGPointZero, image.size}];
    dragView.center  = self.view.center;
        [self.view addSubview:dragView];
    
//     给dragView添加拖拽手势
        UIPanGestureRecognizer *recognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
        [dragView addGestureRecognizer:recognizer];

}
- (void)handlePan:(UIPanGestureRecognizer *)recognizer {

    // 拖拽
    CGPoint translation = [recognizer translationInView:self.view];
    recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x,
                                         recognizer.view.center.y + translation.y);
    [recognizer setTranslation:CGPointMake(0, 0) inView:self.view];

// 关闭CoreAnimation实时动画绘制(核心)
    [CATransaction setDisableActions:YES];
    _movedMask.position = recognizer.view.center;

}
- (void)animationShow{
    [self UpdatingView];
}
- (void)animationHide{
    [UIView animateWithDuration:1.0 animations:^{
//        将雪花动画设置成透明 或者移出去
    } completion:^(BOOL finished) {
        NSLog(@"updatinganimation--hide");
    }];
}
- (void)delayRunEvent:(id)object {
    if (a == 0) {
        NSLog(@"3-----3");
    NSLog(@"%@",object);
    self.getWeatherData.cityStr = object;
    
    [self.getWeatherData getData];

    }
    else
    {
        NSLog(@"zhix");
    }
    a = a + 1;
}
- (void)pullUpEvent{
    ForecastControllerViewController *forecastCV = [[ForecastControllerViewController alloc]initWithArray:self.getWeatherData.weatherData.week.oneWeek];
    forecastCV.transitioningDelegate = self;
    [self presentViewController:forecastCV
                       animated:YES
                     completion:^{}];
    
}
- (void)sucess:(BOOL)sucess{
    if (sucess) {

        WeatherData *dic0 = [[WeatherData alloc]initWithDictionary:self.getWeatherData.weather];
        if (dic0.today.temp == nil) {
            a = 0;
            [self performSelector:@selector(delayRunEvent:)
                       withObject:self.cityName
                       afterDelay:0.3f];
        }else{
        self.weatherView.today = dic0.today;
        self.weatherView.weekForcast = dic0.week;
        self.weatherView.cityName = self.cityCNName;
        [_updatingHUD hide:YES];
        [self.weatherView show];
        }
    }
}
- (void)pullDownToRefreshData
{
    [self.weatherView hide];
    [_updatingHUD show:YES];
    [self.locationManager start];
    a = 0;
   
}

//状态栏
-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleDefault;
}
# pragma mark - 隐藏状态栏
- (BOOL)prefersStatusBarHidden
{
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
